<template>
  <v-main class="d-flex justify-center flex-fill overflow-y-auto">
    <v-container class="my-8 px-4" style="max-width: 1000px">
      <!-- 标题区域 -->
      <div class="text-center mb-8">
        <h1 class="text-h4 text-primary font-weight-bold mb-2">留言板</h1>
        <p class="text-body-1 text-grey-darken-1">分享您的想法与建议，让我们一起创造更美好的体验</p>
      </div>

      <!-- 留言表单 -->
      <v-card class="mb-6" :rounded="false" color="white" elevation="0">
        <v-card-title class="d-flex align-center bg-blue-lighten-5">
          <v-icon icon="mdi-pencil" class="mr-2 text-primary"></v-icon>
          <span class="text-h6 font-weight-bold">写下留言</span>
        </v-card-title>

        <v-card-text class="pa-6">
          <form @submit.prevent="submitMessage">
            <v-text-field
              v-model="messageForm.name"
              placeholder="请输入您的昵称"
              :rules="[(v) => !!v || '昵称不能为空']"
              variant="outlined"
              density="comfortable"
              class="mb-4 neu-input"
            ></v-text-field>

            <v-text-field
              v-model="messageForm.email"
              placeholder="请输入您的电子邮箱（选填）"
              type="email"
              :rules="[
                (v) =>
                  !v || /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(v) || '请输入有效的电子邮箱'
              ]"
              variant="outlined"
              density="comfortable"
              class="mb-4 neu-input"
            ></v-text-field>

            <v-textarea
              v-model="messageForm.content"
              placeholder="请输入您的留言内容..."
              :rules="[
                (v) => !!v || '留言内容不能为空',
                (v) => v.length <= 500 || '留言内容不能超过500字'
              ]"
              rows="4"
              maxlength="500"
              counter
              variant="outlined"
              density="comfortable"
              class="mb-4 neu-input"
            ></v-textarea>

            <v-btn
              type="submit"
              block
              :loading="isSubmitting"
              :disabled="isSubmitting"
              color="primary"
              size="large"
            >
              {{ isSubmitting ? '提交中...' : '提交留言' }}
            </v-btn>
          </form>
        </v-card-text>
      </v-card>

      <!-- 留言列表 -->
      <v-card class="mb-6" :rounded="false" color="blue-lighten-5" elevation="0">
        <v-card-title class="d-flex align-center justify-space-between bg-blue-lighten-5">
          <div class="d-flex align-center">
            <v-icon icon="mdi-chat" class="mr-2 text-primary"></v-icon>
            <span class="text-h6 font-weight-bold">留言列表</span>
          </div>
          <v-chip color="primary" variant="outlined">{{ totalCount }}条留言</v-chip>
        </v-card-title>

        <!-- 搜索框 -->
        <!-- <div class="bg-grey-lighten-4 pa-4">
          <v-text-field
            class="neu-input"
            v-model="searchQuery"
            placeholder="搜索留言内容..."
            variant="outlined"
            density="comfortable"
            hide-details
            prepend-inner-icon="mdi-magnify"
            clearable
            @update:model-value="handleSearch"
          ></v-text-field>
        </div> -->

        <v-card-text class="pa-0">
          <v-list class="pa-0">
            <!-- 加载状态 -->
            <template v-if="isLoading">
              <div class="d-flex justify-center align-center py-16">
                <v-progress-circular indeterminate color="primary" size="48"></v-progress-circular>
                <span class="ml-4 text-grey">加载留言中...</span>
              </div>
            </template>

            <!-- 留言列表 -->
            <template v-else-if="messages.length > 0">
              <v-list-item v-for="message in messages" :key="message.id" class="border-b">
                <template #prepend>
                  <v-avatar class="mr-4">
                    <v-img
                      :src="`https://picsum.photos/seed/${message.id}/200/200`"
                      alt="用户头像"
                    ></v-img>
                  </v-avatar>
                </template>

                <v-list-item-title class="font-weight-bold text-grey-darken-3">
                  {{ message.name }}
                </v-list-item-title>
                <v-list-item-content class="mt-2">
                  <p class="text-body-1 text-grey-darken-2 mb-0">
                    {{ message.content }}
                  </p>
                </v-list-item-content>
                <v-list-item-subtitle class="text-grey">
                  <div class="comment-functions mt-2">
                    <div class="mr-6">{{ formatDate(message.createdAt) }}</div>
                    <div
                      class="pointer mr-6"
                      :class="message.liked ? 'text-primary' : ''"
                      @click="handleLike(message.id)"
                    >
                      <v-icon size="16" icon="mdi-thumb-up" class="mr-1"></v-icon>
                      {{ 3 }}
                    </div>
                    <div class="pointer" @click="handleLike(message.id)">回复</div>
                  </div>
                </v-list-item-subtitle>
              </v-list-item>
            </template>

            <!-- 空状态 -->
            <template v-else>
              <div class="d-flex flex-column align-center justify-center py-16 text-center">
                <v-icon
                  icon="mdi-comment-off-outline"
                  size="64"
                  color="grey-lighten-1"
                  class="mb-4"
                ></v-icon>
                <h3 class="text-h6 font-weight-medium text-grey-darken-1 mb-2">暂无留言</h3>
                <p class="text-body-2 text-grey mb-4">成为第一个留言的人，分享您的想法和建议！</p>
                <v-btn color="primary" @click="scrollToForm">
                  <v-icon icon="mdi-plus" class="mr-2"></v-icon>
                  写下第一条留言
                </v-btn>
              </div>
            </template>
          </v-list>
        </v-card-text>

        <!-- 分页 -->
        <v-card-actions
          v-if="messages.length > 0"
          class="justify-center pa-4 bg-grey-lighten-4 my-4 py-2"
        >
          <v-pagination
            v-model="currentPage"
            :length="totalPages"
            :total-visible="7"
            @update:model-value="handlePageChange"
          ></v-pagination>
        </v-card-actions>
      </v-card>
    </v-container>
  </v-main>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import MessageBox from '@/components/Message'
import { getMessages, createMessage } from '@/services/message.service'
import type { Message } from '@/services/message.service'

// 留言表单数据
const messageForm = ref({
  name: '',
  email: '',
  content: ''
})

// 提交状态
const isSubmitting = ref(false)

// 加载状态
const isLoading = ref(false)

// 留言列表数据
const messages = ref<Message[]>([])
const allMessages = ref<Message[]>([])

// 分页数据
const currentPage = ref(1)
const itemsPerPage = ref(10)
const totalPages = ref(1)
const totalCount = ref(0)

// 搜索功能
const searchQuery = ref('')

// 格式化日期
function formatDate(dateString: string): string {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - date.getTime())
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  // 格式化时间显示
  const formatTime = () => {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${hours}:${minutes}`
  }

  // 相对时间显示
  if (diffDays === 0) {
    return `今天 ${formatTime()}`
  } else if (diffDays === 1) {
    return `昨天 ${formatTime()}`
  } else if (diffDays < 7) {
    return `${diffDays}天前 ${formatTime()}`
  } else {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day} ${formatTime()}`
  }
}

// 提交留言
async function submitMessage() {
  if (isSubmitting.value) return

  isSubmitting.value = true
  try {
    // 调用服务提交留言
    const newMessage = await createMessage(messageForm.value)

    // 添加到留言列表顶部
    messages.value.unshift(newMessage)
    allMessages.value.unshift(newMessage)

    // 更新总数
    totalCount.value++
    totalPages.value = Math.ceil(totalCount.value / itemsPerPage.value)

    // 重置表单
    messageForm.value = {
      name: '',
      email: '',
      content: ''
    }

    // 显示成功消息
    MessageBox({
      message: '留言提交成功！',
      type: 'success',
      duration: 3000
    })

    // 滚动到留言列表顶部
    setTimeout(() => {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }, 500)
  } catch (error) {
    // 显示错误消息
    MessageBox({
      message: '留言提交失败，请稍后再试！',
      type: 'error',
      duration: 3000
    })
    console.error('提交留言失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

function handleLike(messageId: number) {
  // 模拟点赞功能
  console.log(`点赞留言 ${messageId}`)
}
// 处理分页变化
function handlePageChange(page: number) {
  currentPage.value = page
  applyPagination()
}

// 处理搜索
function handleSearch() {
  currentPage.value = 1
  applyPagination()
}

// 应用分页和搜索
function applyPagination() {
  let filteredMessages = allMessages.value

  // 应用搜索过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim()
    filteredMessages = allMessages.value.filter(
      (message) =>
        message.content.toLowerCase().includes(query) || message.name.toLowerCase().includes(query)
    )
  }

  // 更新总数
  totalCount.value = filteredMessages.length
  totalPages.value = Math.ceil(totalCount.value / itemsPerPage.value)

  // 应用分页
  const startIndex = (currentPage.value - 1) * itemsPerPage.value
  const endIndex = startIndex + itemsPerPage.value
  messages.value = filteredMessages.slice(startIndex, endIndex)
}

// 加载留言列表
async function loadMessages(page: number = 1) {
  isLoading.value = true
  try {
    // 调用服务获取留言列表
    const result = await getMessages({
      page,
      pageSize: 100 // 获取更多数据用于前端分页和搜索
    })

    allMessages.value = result.list
    totalCount.value = result.total
    totalPages.value = Math.ceil(result.total / itemsPerPage.value)

    // 应用当前分页和搜索
    applyPagination()
  } catch (error) {
    MessageBox({
      message: '加载留言失败，请稍后再试！',
      type: 'error',
      duration: 3000
    })
    console.error('加载留言失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 滚动到表单
function scrollToForm() {
  const formElement = document.querySelector('form')
  if (formElement) {
    formElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}

// 页面加载时获取留言列表
onMounted(() => {
  loadMessages()
})
</script>
<style lang="scss" scoped>
.v-main {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.v-card {
  border-radius: 12px;

  &--variant-outlined {
    border: 1px solid rgba(0, 0, 0, 0.12);
  }
}

.v-list {
  .v-list-item {
    padding: 16px;

    & + .v-list-item {
      border-top: 1px solid rgba(0, 0, 0, 0.12);
    }

    &:hover {
      background-color: rgba(25, 118, 210, 0.04);
    }
  }
}

// 响应式调整
@media (max-width: 960px) {
  .v-container {
    padding: 16px;
  }

  .v-card-title {
    padding: 16px;
  }

  .v-card-text {
    padding: 16px;
  }
}

@media (max-width: 600px) {
  .v-container {
    padding: 12px;
  }

  h1.text-h4 {
    font-size: 1.5rem;
  }

  .v-list-item {
    padding: 12px;

    .v-avatar {
      width: 40px;
      height: 40px;
      margin-right: 12px;
    }
  }

  .v-pagination {
    .v-btn {
      min-width: 32px;
      height: 32px;
      font-size: 0.875rem;
    }
  }
}

.comment-functions {
  display: flex;
  align-items: center;
}
</style>
